<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>食品分析 - 营养健康管理系统</title>
    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 自定义CSS -->
    <link rel="stylesheet" href="../css/styles.css">
</head>
<body class="bg-gray-50">
    <!-- 导航栏 -->
    <nav class="bg-green-600 text-white shadow-lg">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center">
                <svg class="h-10 w-10 mr-3" viewBox="0 0 100 100">
                    <circle cx="50" cy="50" r="45" fill="#4CAF50" />
                    <text x="50" y="55" font-size="20" text-anchor="middle" fill="white">营养</text>
                    <path d="M30,70 Q50,90 70,70" stroke="white" stroke-width="3" fill="none" />
                </svg>
                <h1 class="text-xl font-bold">营养健康管理系统</h1>
            </div>
            <div class="hidden md:flex space-x-6">
                <a href="../index.html" class="hover:text-green-200">首页</a>
                <a href="food-analysis.html" class="hover:text-green-200 border-b-2 border-white">食品分析</a>
                <a href="health-profile.html" class="hover:text-green-200">健康档案</a>
                <a href="diet-records.html" class="hover:text-green-200">饮食记录</a>
                <a href="nutrition-knowledge.html" class="hover:text-green-200">营养知识</a>
            </div>
            <div class="flex items-center space-x-4">
                <a href="login.html" class="hover:text-green-200">登录</a>
                <a href="register.html" class="bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-100">注册</a>
            </div>
        </div>
    </nav>

    <!-- 页面标题 -->
    <div class="bg-green-500 text-white py-8">
        <div class="container mx-auto px-4">
            <h2 class="text-3xl font-bold">食品分析</h2>
            <p class="mt-2">上传食品图片，获取详细的营养成分分析</p>
        </div>
    </div>

    <!-- 主要内容 -->
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- 左侧：上传区域 -->
            <div class="bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-xl font-semibold mb-4 text-gray-800">上传食品图片</h3>
                <p class="text-gray-600 mb-6">请上传清晰的食品图片，我们的AI系统将自动识别并分析其营养成分</p>
                
                <!-- 上传区域 -->
                <div class="upload-area hover-scale mb-6">
                    <div class="flex flex-col items-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-green-500 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                        </svg>
                        <p class="text-lg font-medium text-gray-700">点击或拖放图片到这里</p>
                        <p class="text-sm text-gray-500 mt-2">支持 JPG, PNG 格式，最大 10MB</p>
                    </div>
                </div>
                
                <!-- 或者分割线 -->
                <div class="flex items-center my-6">
                    <div class="flex-grow border-t border-gray-300"></div>
                    <span class="flex-shrink mx-4 text-gray-500">或者</span>
                    <div class="flex-grow border-t border-gray-300"></div>
                </div>
                
                <!-- 条形码扫描 -->
                <div class="mb-6">
                    <h4 class="font-medium text-gray-700 mb-2">扫描食品条形码</h4>
                    <button class="bg-green-100 hover:bg-green-200 text-green-700 px-4 py-2 rounded-lg flex items-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z" />
                        </svg>
                        打开扫码器
                    </button>
                </div>
                
                <!-- 手动搜索 -->
                <div>
                    <h4 class="font-medium text-gray-700 mb-2">手动搜索食品</h4>
                    <div class="flex">
                        <input type="text" placeholder="输入食品名称" class="form-input flex-grow rounded-l-lg border-r-0">
                        <button class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-r-lg">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：分析结果 -->
            <div class="bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-xl font-semibold mb-4 text-gray-800">营养成分分析</h3>
                
                <!-- 初始状态 -->
                <div id="initial-state" class="text-center py-16">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-gray-400 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    <p class="text-gray-500">请上传食品图片或搜索食品以查看分析结果</p>
                </div>
                
                <!-- 加载状态 -->
                <div id="loading-state" class="text-center py-16 hidden">
                    <div class="loading-spinner mx-auto mb-6"></div>
                    <p class="text-gray-600 text-lg font-medium loading-text">正在分析中</p>
                    <p class="text-gray-500 mt-2">AI 正在识别食品并分析营养成分</p>
                </div>
                
                <!-- 结果状态 -->
                <div id="result-state" class="hidden">
                    <!-- 食品信息 -->
                    <div class="flex items-center mb-6">
                        <div class="w-20 h-20 bg-gray-200 rounded-lg mr-4">
                            <img id="result-image" src="" alt="食品图片" class="w-full h-full object-cover rounded-lg">
                        </div>
                        <div>
                            <h4 id="food-name" class="text-lg font-semibold">食品名称</h4>
                            <p id="food-category" class="text-gray-500">食品类别</p>
                        </div>
                    </div>
                    
                    <!-- 营养成分卡片 -->
                    <div class="nutrition-card mb-6">
                        <div class="nutrition-header">
                            <h4 class="font-semibold">基本营养成分</h4>
                            <p class="text-sm">每100克</p>
                        </div>
                        <div class="nutrition-body">
                            <div class="nutrition-item">
                                <span>热量</span>
                                <span id="calories">0 kcal</span>
                            </div>
                            <div class="nutrition-item">
                                <span>蛋白质</span>
                                <span id="protein">0 g</span>
                            </div>
                            <div class="nutrition-item">
                                <span>脂肪</span>
                                <span id="fat">0 g</span>
                            </div>
                            <div class="nutrition-item">
                                <span>碳水化合物</span>
                                <span id="carbs">0 g</span>
                            </div>
                            <div class="nutrition-item">
                                <span>膳食纤维</span>
                                <span id="fiber">0 g</span>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 维生素和矿物质 -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="nutrition-card">
                            <div class="nutrition-header">
                                <h4 class="font-semibold">维生素</h4>
                            </div>
                            <div class="nutrition-body" id="vitamins-container">
                                <!-- 维生素内容将通过JS动态添加 -->
                                <div class="text-center text-gray-500 py-2">暂无数据</div>
                            </div>
                        </div>
                        
                        <div class="nutrition-card">
                            <div class="nutrition-header">
                                <h4 class="font-semibold">矿物质</h4>
                            </div>
                            <div class="nutrition-body" id="minerals-container">
                                <!-- 矿物质内容将通过JS动态添加 -->
                                <div class="text-center text-gray-500 py-2">暂无数据</div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 操作按钮 -->
                    <div class="mt-6 flex justify-end space-x-4">
                        <button class="border border-green-600 text-green-600 px-4 py-2 rounded-lg hover:bg-green-50">
                            添加到饮食记录
                        </button>
                        <button class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                            获取健康建议
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 相关食品推荐 -->
        <div class="mt-8">
            <h3 class="text-xl font-semibold mb-4 text-gray-800">相关食品推荐</h3>
            <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                <!-- 推荐食品1 -->
                <div class="bg-white p-4 rounded-lg shadow-md hover-scale">
                    <div class="h-32 bg-gray-200 rounded-lg mb-3">
                        <svg class="w-full h-full object-cover rounded-lg" viewBox="0 0 300 200">
                            <rect width="300" height="200" fill="#f8f8f8" />
                            <circle cx="150" cy="100" r="70" fill="#e53935" />
                            <path d="M150,30 Q180,10 180,60" stroke="#43a047" stroke-width="6" fill="none" />
                            <text x="150" y="170" font-size="20" text-anchor="middle" fill="#333">苹果</text>
                        </svg>
                    </div>
                    <h4 class="font-medium">苹果</h4>
                    <p class="text-sm text-gray-500">52 kcal/100g</p>
                </div>
                
                <!-- 推荐食品2 -->
                <div class="bg-white p-4 rounded-lg shadow-md hover-scale">
                    <div class="h-32 bg-gray-200 rounded-lg mb-3">
                        <svg class="w-full h-full object-cover rounded-lg" viewBox="0 0 300 200">
                            <rect width="300" height="200" fill="#f8f8f8" />
                            <path d="M100,150 Q150,50 250,100" stroke="#FFD600" stroke-width="40" stroke-linecap="round" fill="none" />
                            <path d="M100,150 Q150,50 250,100" stroke="#FBC02D" stroke-width="35" stroke-linecap="round" fill="none" />
                            <text x="150" y="170" font-size="20" text-anchor="middle" fill="#333">香蕉</text>
                        </svg>
                    </div>
                    <h4 class="font-medium">香蕉</h4>
                    <p class="text-sm text-gray-500">89 kcal/100g</p>
                </div>
                
                <!-- 推荐食品3 -->
                <div class="bg-white p-4 rounded-lg shadow-md hover-scale">
                    <div class="h-32 bg-gray-200 rounded-lg mb-3">
                        <svg class="w-full h-full object-cover rounded-lg" viewBox="0 0 300 200">
                            <rect width="300" height="200" fill="#f8f8f8" />
                            <circle cx="150" cy="100" r="70" fill="#FF9800" />
                            <path d="M150,30 Q180,10 180,60" stroke="#43a047" stroke-width="6" fill="none" />
                            <path d="M150,100 L150,170" stroke="#FFB74D" stroke-width="2" />
                            <path d="M120,100 L180,100" stroke="#FFB74D" stroke-width="2" />
                            <text x="150" y="170" font-size="20" text-anchor="middle" fill="#333">橙子</text>
                        </svg>
                    </div>
                    <h4 class="font-medium">橙子</h4>
                    <p class="text-sm text-gray-500">47 kcal/100g</p>
                </div>
                
                <!-- 推荐食品4 -->
                <div class="bg-white p-4 rounded-lg shadow-md hover-scale">
                    <div class="h-32 bg-gray-200 rounded-lg mb-3">
                        <svg class="w-full h-full object-cover rounded-lg" viewBox="0 0 300 200">
                            <rect width="300" height="200" fill="#f8f8f8" />
                            <path d="M150,60 Q200,100 150,150 Q100,100 150,60" fill="#e53935" />
                            <circle cx="140" cy="90" r="5" fill="#FFEB3B" />
                            <circle cx="160" cy="90" r="5" fill="#FFEB3B" />
                            <circle cx="150" cy="110" r="5" fill="#FFEB3B" />
                            <circle cx="130" cy="110" r="5" fill="#FFEB3B" />
                            <circle cx="170" cy="110" r="5" fill="#FFEB3B" />
                            <path d="M150,60 Q160,40 170,50" stroke="#43a047" stroke-width="6" fill="none" />
                            <text x="150" y="170" font-size="20" text-anchor="middle" fill="#333">草莓</text>
                        </svg>
                    </div>
                    <h4 class="font-medium">草莓</h4>
                    <p class="text-sm text-gray-500">33 kcal/100g</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-green-800 text-white py-10 mt-12">
        <div class="container mx-auto px-4">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <div>
                    <h3 class="text-lg font-semibold mb-4">关于我们</h3>
                    <p class="text-green-200">营养健康管理系统致力于通过先进技术帮助用户了解食品营养成分，提供个性化健康建议，促进健康生活方式。</p>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">快速链接</h3>
                    <ul class="space-y-2 text-green-200">
                        <li><a href="../index.html" class="hover:text-white">首页</a></li>
                        <li><a href="food-analysis.html" class="hover:text-white">食品分析</a></li>
                        <li><a href="health-profile.html" class="hover:text-white">健康档案</a></li>
                        <li><a href="diet-records.html" class="hover:text-white">饮食记录</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">联系我们</h3>
                    <ul class="space-y-2 text-green-200">
                        <li>邮箱：contact@nutrition-health.com</li>
                        <li>电话：400-123-4567</li>
                        <li>地址：北京市海淀区中关村大街1号</li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-lg font-semibold mb-4">关注我们</h3>
                    <div class="flex space-x-4">
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M22.675 0h-21.35c-.732 0-1.325.593-1.325 1.325v21.351c0 .731.593 1.324 1.325 1.324h11.495v-9.294h-3.128v-3.622h3.128v-2.671c0-3.1 1.893-4.788 4.659-4.788 1.325 0 2.463.099 2.795.143v3.24l-1.918.001c-1.504 0-1.795.715-1.795 1.763v2.313h3.587l-.467 3.622h-3.12v9.293h6.116c.73 0 1.323-.593 1.323-1.325v-21.35c0-.732-.593-1.325-1.325-1.325z"/>
                            </svg>
                        </a>
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M23.953 4.57a10 10 0 01-2.825.775 4.958 4.958 0 002.163-2.723 10.054 10.054 0 01-3.127 1.184 4.92 4.92 0 00-8.384 4.482C7.69 8.095 4.067 6.13 1.64 3.162a4.822 4.822 0 00-.666 2.475c0 1.71.87 3.213 2.188 4.096a4.904 4.904 0 01-2.228-.616v.06a4.923 4.923 0 003.946 4.827 4.996 4.996 0 01-2.212.085 4.936 4.936 0 004.604 3.417 9.867 9.867 0 01-6.102 2.105c-.39 0-.779-.023-1.17-.067a13.995 13.995 0 007.557 2.209c9.053 0 13.998-7.496 13.998-13.985 0-.21 0-.42-.015-.63A9.935 9.935 0 0024 4.59z"/>
                            </svg>
                        </a>
                        <a href="#" class="text-green-200 hover:text-white">
                            <svg class="h-6 w-6" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M12 0C8.74 0 8.333.015 7.053.072 5.775.132 4.905.333 4.14.63c-.789.306-1.459.717-2.126 1.384S.935 3.35.63 4.14C.333 4.905.131 5.775.072 7.053.012 8.333 0 8.74 0 12s.015 3.667.072 4.947c.06 1.277.261 2.148.558 2.913.306.788.717 1.459 1.384 2.126.667.666 1.336 1.079 2.126 1.384.766.296 1.636.499 2.913.558C8.333 23.988 8.74 24 12 24s3.667-.015 4.947-.072c1.277-.06 2.148-.262 2.913-.558.788-.306 1.459-.718 2.126-1.384.666-.667 1.079-1.335 1.384-2.126.296-.765.499-1.636.558-2.913.06-1.28.072-1.687.072-4.947s-.015-3.667-.072-4.947c-.06-1.277-.262-2.149-.558-2.913-.306-.789-.718-1.459-1.384-2.126C21.319 1.347 20.651.935 19.86.63c-.765-.297-1.636-.499-2.913-.558C15.667.012 15.26 0 12 0zm0 2.16c3.203 0 3.585.016 4.85.071 1.17.055 1.805.249 2.227.415.562.217.96.477 1.382.896.419.42.679.819.896 1.381.164.422.36 1.057.413 2.227.057 1.266.07 1.646.07 4.85s-.015 3.585-.074 4.85c-.061 1.17-.256 1.805-.421 2.227-.224.562-.479.96-.899 1.382-.419.419-.824.679-1.38.896-.42.164-1.065.36-2.235.413-1.274.057-1.649.07-4.859.07-3.211 0-3.586-.015-4.859-.074-1.171-.061-1.816-.256-2.236-.421-.569-.224-.96-.479-1.379-.899-.421-.419-.69-.824-.9-1.38-.165-.42-.359-1.065-.42-2.235-.045-1.26-.061-1.649-.061-4.844 0-3.196.016-3.586.061-4.861.061-1.17.255-1.814.42-2.234.21-.57.479-.96.9-1.381.419-.419.81-.689 1.379-.898.42-.166 1.051-.361 2.221-.421 1.275-.045 1.65-.06 4.859-.06l.045.03zm0 3.678c-3.405 0-6.162 2.76-6.162 6.162 0 3.405 2.76 6.162 6.162 6.162 3.405 0 6.162-2.76 6.162-6.162 0-3.405-2.76-6.162-6.162-6.162zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4zm7.846-10.405c0 .795-.646 1.44-1.44 1.44-.795 0-1.44-.646-1.44-1.44 0-.794.646-1.439 1.44-1.439.793-.001 1.44.645 1.44 1.439z"/>
                            </svg>
                        </a>
                    </div>
                </div>
            </div>
            <div class="border-t border-green-700 mt-8 pt-6 text-center text-green-300">
                <p>&copy; 2025 营养健康管理系统 版权所有</p>
            </div>
        </div>
    </footer>

    <!-- JavaScript -->
    <script src="../js/main.js"></script>
    <script src="../js/api-service.js"></script>
    <script>
        // 食品分析页面特定脚本
        document.addEventListener('DOMContentLoaded', function() {
            // 获取页面元素
            const uploadArea = document.querySelector('.upload-area');
            const initialState = document.getElementById('initial-state');
            const loadingState = document.getElementById('loading-state');
            const resultState = document.getElementById('result-state');
            const searchInput = document.querySelector('input[placeholder="输入食品名称"]');
            const searchButton = searchInput ? searchInput.nextElementSibling : null;
            
            // 当前用户ID (实际应用中应从登录状态获取)
            const currentUserId = localStorage.getItem('userId') || 1; // 默认使用ID为1的用户
            // 处理图片上传
            function handleImageUpload(file) {
                // 检查文件类型
                if (!file.type.match('image.*')) {
                    showToast('请上传图片文件（JPG, PNG 等格式）', 'error');
                    return;
                }
                
                // 检查文件大小
                if (file.size > 10 * 1024 * 1024) { // 10MB
                    showToast('图片大小不能超过 10MB', 'error');
                    return;
                }
                
                // 显示加载状态
                showLoadingState();
                
                // 创建FormData对象
                const formData = new FormData();
                formData.append('image', file);
                
                // 显示上传中的提示
                const loadingTexts = [
                    "正在上传图片...",
                    "AI 正在识别食品...",
                    "正在分析营养成分...",
                    "正在生成健康建议..."
                ];
                
                let currentTextIndex = 0;
                const loadingTextElement = document.querySelector('#loading-state p.text-lg');
                const loadingInterval = setInterval(() => {
                    if (loadingTextElement) {
                        loadingTextElement.textContent = loadingTexts[currentTextIndex];
                        currentTextIndex = (currentTextIndex + 1) % loadingTexts.length;
                    }
                }, 3000);
                
                // 调用API分析食品
                apiService.foodAnalysis.analyzeFood(formData)
                    .then(result => {
                        // 清除加载文本切换
                        clearInterval(loadingInterval);
                        
                        // 显示分析结果
                        displayAnalysisResult(result);
                    })
                    .catch(error => {
                        // 清除加载文本切换
                        clearInterval(loadingInterval);
                        
                        console.error('食品分析失败:', error);
                        showToast('分析失败，请稍后再试', 'error');
                        
                        // 返回初始状态
                        initialState.classList.remove('hidden');
                        loadingState.classList.add('hidden');
                    });
            }
            
            // 显示加载状态
            function showLoadingState() {
                initialState.classList.add('hidden');
                resultState.classList.add('hidden');
                loadingState.classList.remove('hidden');
            }
            
            // 显示分析结果
            function displayAnalysisResult(result) {
                // 隐藏加载状态
                loadingState.classList.add('hidden');
                initialState.classList.add('hidden');
                resultState.classList.remove('hidden');
                
                // 设置食品信息
                document.getElementById('food-name').textContent = result.name || '未知食品';
                document.getElementById('food-category').textContent = result.category || '未分类';
                
                // 设置食品图片
                const resultImage = document.getElementById('result-image');
                if (resultImage && result.imageUrl) {
                    resultImage.src = result.imageUrl;
                    resultImage.alt = result.name;
                }
                
                // 设置基本营养成分
                document.getElementById('calories').textContent = `${result.calories || 0} kcal`;
                document.getElementById('protein').textContent = `${result.protein || 0} g`;
                document.getElementById('fat').textContent = `${result.fat || 0} g`;
                document.getElementById('carbs').textContent = `${result.carbs || 0} g`;
                document.getElementById('fiber').textContent = `${result.fiber || 0} g`;
                
                // 设置维生素
                const vitaminsContainer = document.getElementById('vitamins-container');
                if (vitaminsContainer) {
                    vitaminsContainer.innerHTML = '';
                    
                    if (result.vitamins && Object.keys(result.vitamins).length > 0) {
                        Object.entries(result.vitamins).forEach(([name, value]) => {
                            const item = document.createElement('div');
                            item.className = 'nutrition-item';
                            item.innerHTML = `
                                <span>维生素 ${name}</span>
                                <span>${value}</span>
                            `;
                            vitaminsContainer.appendChild(item);
                        });
                    } else {
                        vitaminsContainer.innerHTML = '<div class="text-center text-gray-500 py-2">暂无数据</div>';
                    }
                }
                
                // 设置矿物质
                const mineralsContainer = document.getElementById('minerals-container');
                if (mineralsContainer) {
                    mineralsContainer.innerHTML = '';
                    
                    if (result.minerals && Object.keys(result.minerals).length > 0) {
                        Object.entries(result.minerals).forEach(([name, value]) => {
                            const item = document.createElement('div');
                            item.className = 'nutrition-item';
                            item.innerHTML = `
                                <span>${name}</span>
                                <span>${value}</span>
                            `;
                            mineralsContainer.appendChild(item);
                        });
                    } else {
                        mineralsContainer.innerHTML = '<div class="text-center text-gray-500 py-2">暂无数据</div>';
                    }
                }
                
                // 设置操作按钮事件
                const addToDietButton = resultState.querySelector('button:first-of-type');
                if (addToDietButton) {
                    addToDietButton.onclick = () => addToDietRecord(result);
                }
                
                const getAdviceButton = resultState.querySelector('button:last-of-type');
                if (getAdviceButton) {
                    getAdviceButton.onclick = () => getHealthAdvice(result);
                }
            }
            
            // 添加到饮食记录
            function addToDietRecord(foodData) {
                // 显示加载状态
                showToast('正在添加到饮食记录...', 'info');
                
                // 准备记录数据
                const recordData = {
                    userId: currentUserId,
                    date: new Date().toISOString().split('T')[0],
                    mealType: 'LUNCH', // 默认为午餐
                    foodItems: [{
                        name: foodData.name,
                        quantity: 1,
                        calories: foodData.calories,
                        protein: foodData.protein,
                        fat: foodData.fat,
                        carbs: foodData.carbs
                    }]
                };
                
                // 调用API添加饮食记录
                apiService.dietRecord.addDietRecord(currentUserId, recordData)
                    .then(() => {
                        showToast('已添加到饮食记录！', 'success');
                    })
                    .catch(error => {
                        console.error('添加饮食记录失败:', error);
                        showToast('添加失败，请稍后再试', 'error');
                    });
            }
            
            // 获取健康建议
            function getHealthAdvice(foodData) {
                // 显示加载状态
                showToast('正在获取健康建议...', 'info');
                
                // 这里应该调用API获取健康建议
                // 由于API可能尚未实现，我们使用模拟数据
                setTimeout(() => {
                    const advice = `基于您的健康档案和当前饮食情况，${foodData.name}是一个不错的选择。它含有丰富的维生素C和膳食纤维，有助于增强免疫力和促进消化。建议适量食用，每日不超过2个。`;
                    alert(advice);
                    showToast('已获取健康建议！', 'success');
                }, 1000);
            }
            
            // 搜索食品
            function searchFoods(query) {
                if (!query.trim()) return;
                
                // 显示加载状态
                showLoadingState();
                
                // 调用API搜索食品
                apiService.foodAnalysis.searchFoods(query)
                    .then(results => {
                        if (results.length === 0) {
                            showToast('未找到相关食品', 'info');
                            initialState.classList.remove('hidden');
                            loadingState.classList.add('hidden');
                            return;
                        }
                        
                        // 显示第一个结果
                        apiService.foodAnalysis.getFoodDetails(results[0].id)
                            .then(displayAnalysisResult)
                            .catch(error => {
                                console.error('获取食品详情失败:', error);
                                showToast('获取食品详情失败', 'error');
                                initialState.classList.remove('hidden');
                                loadingState.classList.add('hidden');
                            });
                    })
                    .catch(error => {
                        console.error('搜索食品失败:', error);
                        showToast('搜索失败，请稍后再试', 'error');
                        initialState.classList.remove('hidden');
                        loadingState.classList.add('hidden');
                    });
            }
            
            // 初始化上传区域
            if (uploadArea) {
                uploadArea.addEventListener('click', function() {
                    const fileInput = document.createElement('input');
                    fileInput.type = 'file';
                    fileInput.accept = 'image/*';
                    fileInput.style.display = 'none';
                    
                    fileInput.addEventListener('change', function(e) {
                        if (e.target.files && e.target.files[0]) {
                            handleImageUpload(e.target.files[0]);
                        }
                    });
                    
                    document.body.appendChild(fileInput);
                    fileInput.click();
                    document.body.removeChild(fileInput);
                });
                
                // 拖放功能
                uploadArea.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    this.classList.add('active');
                });
                
                uploadArea.addEventListener('dragleave', function() {
                    this.classList.remove('active');
                });
                
                uploadArea.addEventListener('drop', function(e) {
                    e.preventDefault();
                    this.classList.remove('active');
                    
                    if (e.dataTransfer.files && e.dataTransfer.files[0]) {
                        handleImageUpload(e.dataTransfer.files[0]);
                    }
                });
            }
            
            // 初始化搜索功能
            if (searchButton && searchInput) {
                searchButton.addEventListener('click', function() {
                    searchFoods(searchInput.value);
                });
                
                searchInput.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        searchFoods(this.value);
                    }
                });
            }
        });
    </script>
</body>
</html>